/**
 * 
 */
package qmlt.learning.decisiontree.control;

import java.util.HashMap;
import java.util.Map;

import qmlt.dataset.DataSet;
import qmlt.dataset.Instance;
import qmlt.dataset.utils.DataSetUtils;
import qmlt.learning.decisiontree.DecisionTree;
import qmlt.learning.decisiontree.Node;
import qmlt.learning.decisiontree.utils.DecisionTreeUtils;

/**
 * @author quyin
 */
public class ReducedErrorPruner implements PruneController
{
    private DecisionTree          tree;

    private DataSet               validateSet;

    private Map<Instance, Object> predictions = new HashMap<Instance, Object>();

    private Node                  nodeToPrune;

    private float                 bestImprove;

    public ReducedErrorPruner(DataSet validateSet)
    {
        this.validateSet = validateSet;
    }

    @Override
    public void prune(DecisionTree tree)
    {
        this.tree = tree;
        while (true)
        {
            predictValidateSet();

            nodeToPrune = null;
            bestImprove = 0;
            pruneHelper(this.tree.getRoot());
            if (nodeToPrune != null)
                doPrune(nodeToPrune);
            else
                break;
        }
    }

    private void predictValidateSet()
    {
        predictions.clear();
        for (Instance inst : validateSet.getInstances())
        {
            Object p = tree.predict(inst);
            predictions.put(inst, p);
        }
    }

    private void pruneHelper(Node node)
    {
        int improve = tryPrune(node);
        if (improve > bestImprove)
        {
            bestImprove = improve;
            nodeToPrune = node;
        }

        for (Node child : node.children.values())
        {
            pruneHelper(child);
        }
    }

    private int tryPrune(Node node)
    {
        int mislabeled = DecisionTreeUtils.countMislabeled(node, predictions);
        int prunedMislabeled = DecisionTreeUtils.countMislabeledIfPruned(node, DataSetUtils
                .findMajorClass(node.instances));
        return mislabeled - prunedMislabeled;
    }

    private void doPrune(Node nodeToPrune)
    {
        nodeToPrune.children.clear();
        nodeToPrune.targetClass = DataSetUtils.findMajorClass(nodeToPrune.instances);
    }

    @Override
    public DataSet getValidateSet()
    {
        return validateSet;
    }
}
